import { Component, OnInit, HostBinding, ViewChild, ElementRef } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

import {
  ViewerBaseComponent,
  DocToc,
} from '../../shared';

@Component({
  templateUrl: './component-viewer.component.html',
  styleUrls: ['./component-viewer.component.sass'],
})
export class ComponentViewerComponent extends ViewerBaseComponent implements OnInit {
  @HostBinding('class') hostClass = 'fui-layout2-content';

  @HostBinding('id') hostId = 'componentViewer';

  example: string;

  tocs: DocToc[] = [];

  COMPONENT_TOC_ATTRIBUTE = 'fui-docs-example-title';

  TOC_ITEM_CLASS = '.fui-toc-item';

  TOC_ITEM_NAME_ATTRIBUTE = 'fui-toc-name';

  constructor(
    public elem: ElementRef,
    protected route: ActivatedRoute,
  ) {
    super(route);
  }

  ngOnInit() {
    this.route.params.subscribe((params) => {
      this.example = params['path'];
    });
  }

  collectToc() {
    this.tocs = [];

    const tocAttribute = this.COMPONENT_TOC_ATTRIBUTE;
    const exampleTitleElements = document.body.querySelectorAll(
      `[${tocAttribute}]`,
    );

    Array.from(exampleTitleElements).forEach((element: Element) => {
      const exampleTitle = element.getAttribute(tocAttribute);
      this.tocs.push(new DocToc(exampleTitle, encodeURIComponent(exampleTitle)));
    });

    this.collectSubTitle('fui-api-viewer', 'API');
    this.collectSubTitle('fui-model-viewer', 'Model');
  }

  collectSubTitle(selector: string, parent: string) {
    const el = document.querySelector(selector);

    if (el) {
      const parentToc = new DocToc(parent, encodeURIComponent(parent));
      this.tocs.push(parentToc);

      const childs = el.querySelectorAll(this.TOC_ITEM_CLASS);
      Array.from(childs).forEach((child) => {
        parentToc.children.push({
          name: child.getAttribute(this.TOC_ITEM_NAME_ATTRIBUTE),
          id: child.id,
          class: 'sub-title',
          type: (child.querySelector('fui-type-label') as HTMLElement).innerText
            .trim()
            .toLocaleLowerCase(),
        });
      });
    }
  }

  onContentLoaded() {
    this.collectToc();
    this.scrollToView();
  }
}
